package io.xxx.sync.manage

import org.springframework.context.ApplicationContext
import org.springframework.context.ApplicationContextAware
import org.springframework.context.ApplicationEvent
import org.springframework.context.ApplicationListener
import org.springframework.context.support.GenericApplicationContext
import org.springframework.stereotype.Component

class TokenRefreshedEvent(val beanName: String, val bean: Any) : ApplicationEvent(beanName)

@Component
class TokenRefreshHandler : ApplicationListener<TokenRefreshedEvent>, ApplicationContextAware {

    private lateinit var applicationContext: GenericApplicationContext

    override fun onApplicationEvent(event: TokenRefreshedEvent) {
        if (applicationContext.containsBean(event.beanName)) {
            applicationContext.removeBeanDefinition(event.beanName)
        }
        val beanFactory = applicationContext.defaultListableBeanFactory
        beanFactory.registerSingleton(event.beanName, event.bean)
    }

    override fun setApplicationContext(applicationContext: ApplicationContext) {
        this.applicationContext = applicationContext as GenericApplicationContext
    }
}